<!--
 * @Description: 告警联系人管理
-->
<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag"
        @search="searchFormData" @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" :data="tableData" stripe border height="88%" @row-click="handleEdit"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="staffName" label="联系人" />
        <el-table-column prop="alarmTypeName" label="告警类型" />
        <el-table-column width="120" label="操作">
          <template v-if="scope.row.alarmContactsId" slot-scope="scope">
            <el-button class="text-btn-cursor" v-if="judgePermission(20, 'edit')" type="text" size="small"
              @click="edit">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small"
              v-if="judgePermission(20, 'delete')" @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal='false' :title="dialogTitle + '告警联系人信息'" :visible.sync="dialogFormVisible"
        :before-close="cancel" width="40%">
        <el-form ref="formData" :model="formData" :rules="rules" :show-message="canInput" label-width="100px"
          class="demo-ruleForm">
          <el-form-item label="联系人" prop="staffId">
            <el-select class="w100p" filterable clearable v-model="formData.staffId" placeholder="选择联系人">
              <el-option v-for="item in staffList" :key="item.staffId" :label="item.staffName" :value="item.staffId" />
            </el-select>
          </el-form-item>
          <el-form-item label="告警类型" prop="alarmTypeId">
            <el-select class="w100p" filterable clearable v-model="formData.alarmTypeId" placeholder="选择告警类型">
              <el-option v-for="(alarmTypeitem, alarmTypeindex) in alarmTypeList" :key="alarmTypeindex"
                :label="alarmTypeitem.alarmTypeName" :value="alarmTypeitem.alarmTypeId" />
            </el-select>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';

// import ActionBar from "@/components/ActionBar";
// import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/monitoring-alarm/alarm-contact-management";
// import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import monitoringCategoryApi from "@/api/monitoring-alarm/alarm-category-management";
import staffApi from "@/api/basic-info-manage/staff/index";
// import monitoringTemplateApi from "@/api/monitoring-alarm/alarm-template-configuration";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from 'vuex';
export default {
  name: "alarmContactsManage",
  components: { BtnSlot, Pagination, MainSlot, SearchForm },
  mixins: [mymixin],
  data() {
    return {
      unfoldFlag: false,
      btnList: ['add', 'delete'],
      formItemList: [
        {
          label: '联系人',
          type: 'select',
          selectOptions: [],
          param: 'staffId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
      rules: {
        staffId: [
          { required: true, message: "请选择联系人", trigger: "change" }
        ],
        alarmTypeId: [
          { required: true, message: "请选择告警类型", trigger: "change" }
        ]
      },
      // 搜索内容
      searchList: {
        staffId: ''
      },
      // 选中的数据项数组 alarmContactsId组成 (此数组最多为一个)
      selectIdList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      alarmTypeList: [],
      staffList: []
    };
  },
  watch: {
    dialogFormVisible: {
      handler(status) {
        if (!status) {
          this.$refs['formData'].resetFields()
          console.log('重置表单验证')
        }
      }
    },
    nowChanceStau(v) {
      if (v === 'add') {
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        console.log('staffId', staffId);
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        console.log('userList', userList);
        this.formData = {
          staffId: userList.length == 0 ? this.staffList[0].staffName : staffName,
          staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
        }
      }
    }
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    this.search();
    // 获取表格数据
  },
  mounted() {
    this.getselectdatalist();
  },
  methods: {
    //table项是否可以被选中
    selectable(row) {
      return !('index' in row)
    },
    searchFormData(data) {
      this.currentPage = 1;
      this.searchList.staffId = data.staffId;
      this.search();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('staffId') !== -1) {
          let selectOptions = this.staffList.map(data => {
            return {
              text: data.staffName, value: data.staffId
            }
          })
          item.selectOptions = selectOptions;
        };

      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchList
        }
      };
      nowpagereq.getlist(params).then(res => {
        this.loading = false;
        if (res.errCode !== undefined) {
          this.$message.error(res.message || "查询失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
      });
    },
    // 获取下拉框数据 start
    async getselectdatalist() {
      monitoringCategoryApi
        .queryByCondition({
          homeBaseId: sessionStorage.homeBaseId
        })
        .then(res => {
          // this.alarmTypeList = res.data;
          if (res.data !== undefined) {
            this.alarmTypeList = res.data;
          } else this.alarmTypeList = [];
        });
      const { data: staff } = await staffApi.queryByCondition({});
      this.staffList = staff || [];
      this.setFormOptions()
    },
    handleEdit(row) {
      if (row.alarmContactsId) {
        this.formData = { ...row };
        // this.openDialog("edit");
      }
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      let notvalue = true;
      this.selectIdList = list.map(item => {
        if (item.alarmContactsId) {
          return item.alarmContactsId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.selectIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },

    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage();
      }
    },
    delmessage() {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          nowpagereq.dellist(this.selectIdList).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("删除成功");
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        }).catch(() => {
          this.$message("取消删除");
        });
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          nowpagereq.dellist([data.alarmContactsId]).then(res => {
            if (res.success) {
              this.search();
              this.$message.success("删除成功");
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    closeDialog() {
      this.formData = {};
      this.dialogFormVisible = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // this.formData.routePointMapperList = this.tagsList;
            nowpagereq.editlist(this.formData).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.search();
                this.closeDialog();
              } else {
                this.$message.error(res.message || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            nowpagereq.addlist(this.formData).then(res => {
              if (res.success) {
                this.$message.success("新增成功！");
                this.search();
                this.closeDialog();
              } else {
                this.$message.error(res.message || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error res.message || submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss"></style>
